從上一篇 [cURL] 常用的 curl_setopt() 介紹 ,我們已經知道常用 curl_setopt() 的 option 是哪些。 本文以 PATCH 為例,將帶入常用的 curl_setopt()
curl_setopt_array() 可以設定多組 CURLOPT_XXX,因此,改用 curl_setopt_array() 取代 curl_setopt()<?php
// create a new cURL resource
$ch = curl_init();
$payload = json_encode(
  [
    "title" => "Round world",
    "body"  => "hello word",
    "game"  => "5X Ruby",
  ]  
);
$headers = [
  "Content-type: application/json; Charset=UTF-8",
];
// 設定多個 option
curl_setopt_array($ch, [
  // URL to fetch
  CURLOPT_URL => "https://jsonplaceholder.typicode.com/posts/1",
  // 返回字串而不是直接輸出
  CURLOPT_RETURNTRANSFER => true, 
  // custom request method 
  CURLOPT_CUSTOMREQUEST => "PATCH",
  // 設定 HTTP 檔頭(Header)
  CURLOPT_HTTPHEADER => $headers,
  // 設定傳送的檔案 (payload)
  CURLOPT_POSTFIELDS => $payload,
]);
$response = curl_exec($ch);
curl_close($ch);
// do anything you want with your response
var_dump($response);
/* (string)
 * {
 *   "userId": 1,  
 *   "id": 1,
 *   "title": "Round world",
 *   "body": "whatever yu want",
 *   "game": "5X Ruby"
 * }
 */ 
PHP cURL function 提供 Call API 的 function,以及多個 curl_setopt() 的 CURLOPT_XXX 可以使用。PHP cURL Call API 較 stream (串流) Call API 的方式,簡單許多。
下一階段,我們將 Call API 方式執行在 PHP 套件 (Guzzle) 上,那將會是另一個世界.
stream 和 cURL, 這兩個方式在設定上有些共通點,諸如:
1 [cURL] 常用的 curl_setopt() 介紹
2 Guzzle
PHP, cURL, and HTTP POST example?